package com.boxing.utils;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class Utils {

    public static String getToken(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        String token = "";
        for (int i = 0; cookies!= null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if(Contants.COOKIE_TOKEN.equals(cookie.getName())){
                token = cookie.getValue();
                break;
            }
        }
        return token;
    }

    public static String getUserEmailFromSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        return (String) session.getAttribute(getToken(request));
    }

    public static String formatPrice(String price){
        StringBuilder stringBuilder = new StringBuilder(price);
        if (stringBuilder.length() == 2){
            stringBuilder.insert(0,"0");
        }else if (stringBuilder.length() == 1){
            stringBuilder.insert(0,"00");
        }
        return stringBuilder.insert(stringBuilder.length() - 2, ".").toString();
    }

    /**
     * 获取服务器的地址， 包括
     * @return  协议：//ip:端口号/工程目录
     */
    public static String getServerUrl(HttpServletRequest request){
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        return request.getScheme()+"://"+serverName+":"+serverPort+request.getContextPath();
    }
}
